define(['jquery', 'bootstrap', 'backend', 'table', 'form','layui'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'goods/type/index' + location.search,
                    add_url: 'goods/type/add',
                    edit_url: 'goods/type/edit',
                    del_url: 'goods/type/del',
                    multi_url: 'goods/type/multi',
                    table: 'goods_type',
                }
            });

            var table = $("#table");


            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'name', title: __('Name')},
                        {field:'type_params', minWidth:200,title:'参数',formatter:function (data, row) {
                                if(typeof(data) == "undefined"||data.length==0){
                                    var html='<a style="color: #963d3d;" href="javascript:void(0);" data-id="'+row.id+'" onclick="addParams('+row.id+')">关联参数</a>';
                                    return html;
                                }else{
                                    var html=' <a style="color: #963d3d;" href="javascript:void(0);" data-id="'+row.id+'" onclick="addParams('+row.id+')">变更参数</a>';
                                    $.each(data,function(i,j){
                                        html = html + "|"+ j.name;
                                    });
                                    html=html.substr(1);
                                    return html;
                                }
                            }, align: 'center'},
                        {field:'type_spec', minWidth:200,title:'属性',formatter:function(data, row){
                            console.log(data)
                                if(typeof(data) == "undefined"||data.length==0){
                                    var html='<a style="color: #963d3d;" href="javascript:void(0);" data-id="'+row.id+'" onclick="addSpec('+row.id+')">关联属性</a>';
                                    return html;
                                }else{
                                    var html=' <a style="color: #963d3d;" href="javascript:void(0);" data-id="'+row.id+'" onclick="addSpec('+row.id+')">变更属性</a>';
                                    $.each(data,function(i,j){
                                        html = html + "|"+ j.name;
                                    });
                                    html=html.substr(1);
                                    return html;
                                }
                            }, align: 'center'},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            //渲染表单
            layui.use(['form', 'table', 'element'], function () {
                var form = layui.form;
                var table = layui.table;
                var laytpl = layui.laytpl;
                var element = layui.element;
                form.render();


                $(".layui-tab").on('click', '.add-type-class', function (e) {
                    //var getTpl = type_l_tpl.innerHTML;
                    var lastId = $(this).parent().parent().parent().find('tr').last().attr('data-id');
                    var tmpData = {};
                    tmpData.id = parseInt(lastId) + 1;
                    var html =  laytpl('<tr data-id="{{ d.id }}">\n' +
                        '        <td>\n' +
                        '            <input type="hidden" name="type_id[{{ d.id }}]" value="">\n' +
                        '\n' +
                        '            <input type="text" name="type_name[{{ d.id }}]" required value="" lay-verify="required"\n' +
                        '                   placeholder="" autocomplete="off" class="layui-input seller-inline-1">\n' +
                        '        </td>\n' +
                        '        <td>\n' +
                        '            <input type="text" name="type_sort[{{ d.id }}]" required value="100" lay-verify="required"\n' +
                        '                   placeholder="" autocomplete="off" class="layui-input seller-inline-1">\n' +
                        '        </td>\n' +
                        '        <td>\n' +
                        '            <input type="text" name="type_value[{{ d.id }}]" required value=""\n' +
                        '                   lay-verify="required" placeholder="空格分隔" autocomplete="off"\n' +
                        '                   class="layui-input seller-inline-1">\n' +
                        '        </td>\n' +
                        '        <td>\n' +
                        '            <a class="layui-btn layui-btn-xs select-type-class">\n' +
                        '                选择\n' +
                        '            </a>\n' +
                        '            <a class="layui-btn layui-btn-danger layui-btn-xs del-type-class">\n' +
                        '                删除\n' +
                        '            </a>\n' +
                        '        </td>\n' +
                        '    </tr>').render({
                        id: tmpData.id
                    });
                    $("#type_view").append(html);
                    /*laytpl(getTpl).render(tmpData, function (html) {
                        $("#type_view").append(html);
                    });*/
                    form.render();
                });

                $(".layui-tab").on('click', '.add-params-class', function (e) {
                    //var getTpl = params_tpl.innerHTML;
                    var lastId = $(this).parent().parent().parent().find('tr').last().attr('data-id');
                    var tmpData = {};
                    tmpData.id = parseInt(lastId) + 1;
                    var html =  laytpl('<tr data-id="{{ d.id }}">\n' +
                        '        <td>\n' +
                        '            <input type="hidden" name="params_id[{{ d.id }}]" value="">\n' +
                        '\n' +
                        '            <input type="text" name="params_name[{{ d.id }}]" required value="" lay-verify="required"\n' +
                        '                   placeholder="" autocomplete="off" class="layui-input seller-inline-1">\n' +
                        '        </td>\n' +
                        '        <td>\n' +
                        '            <select name="params_type[{{ d.id }}]">\n' +
                        '                <option value="text">文本框</option>\n' +
                        '                <option value="radio">单选框</option>\n' +
                        '                <option value="checkbox">复选框</option>\n' +
                        '            </select>\n' +
                        '        </td>\n' +
                        '        <td>\n' +
                        '            <input type="text" name="params_value[{{ d.id }}]" value=""\n' +
                        '                   placeholder="空格分隔" autocomplete="off"\n' +
                        '                   class="layui-input seller-inline-1">\n' +
                        '        </td>\n' +
                        '        <td>\n' +
                        '            <a class="layui-btn layui-btn-xs select-params-class">\n' +
                        '                选择\n' +
                        '            </a>\n' +
                        '            <a class="layui-btn layui-btn-danger layui-btn-xs del-params-class">\n' +
                        '                删除\n' +
                        '            </a>\n' +
                        '        </td>\n' +
                        '    </tr>').render({
                        id: tmpData.id
                    });
                    $("#params_view").append(html);
                    /*laytpl(getTpl).render(tmpData, function (html) {
                        $("#params_view").append(html);
                    });*/
                    form.render();

                });

                $(".layui-tab").on('click', '.del-type-class,.del-params-class', function (e) {
                    $(this).parent().parent().remove();
                })
                //选择已有参数
                var selectParamsId = 0;
                $(".layui-tab").on('click', '.select-params-class', function (e) {

                    selectParamsId = $(this).parent().parent().attr('data-id');

                    Fast.api.open("goods/Params/select",'选择参数',{
                        callback:function(value){
                            //在回调函数里可以调用你的业务代码实现前端的各种逻辑和效果
                            console.log(value);

                            $("input[name='params_id[" + selectParamsId + "]']").val(value.id);
                            $("input[name='params_name[" + selectParamsId + "]']").val(value.name);
                            $("input[name='params_value[" + selectParamsId + "]']").val(value.value);
                            $("select[name='params_type[" + selectParamsId + "]']").val(value.type);
                            /*if(value.multiple==true){
                                $('#c-related_goods').val(value.url);
                            }else{
                                $('#c-related_goods').val(value.id+'-'+value.goodsname);
                            }*/
                            /*$('#c-related_goods').val(value.url);
                            var urlArr = [];

                            if(values!==''){
                                urlArr.push(values);
                            }
                            urlArr.push(value.url);
                            var result = urlArr.join(",");
                            console.log(urlArr);
                            $('#c-related_goods').val(result).trigger("change").trigger("validate");*/

                        },
                    });



                });
                //监听商品列表页工具条
                /*table.on('tool(paramsTable)', function (obj) { //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
                    var data = obj.data; //获得当前行数据
                    var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
                    if (layEvent === 'selectParams') { //选择
                        $("input[name='params_id[" + selectParamsId + "]']").val(data.id);
                        $("input[name='params_name[" + selectParamsId + "]']").val(data.name);
                        $("input[name='params_value[" + selectParamsId + "]']").val(data.value);
                        $("select[name='params_type[" + selectParamsId + "]']").val(data.type);
                        form.render('select');
                        layer.close(window.box);
                    }
                });*/

                //选择已有属性
                var selectTypeId = 0;
                $(".layui-tab").on('click', '.select-type-class', function (e) {
                    selectTypeId = $(this).parent().parent().attr('data-id');
                    Fast.api.open("goods/Spec/select",'选择参数',{
                        callback:function(value){
                            //在回调函数里可以调用你的业务代码实现前端的各种逻辑和效果
                            console.log(value);

                            var text = '';
                            if (value.spec_value.length > 0) {
                                $.each(value.spec_value, function (i, j) {
                                    if (text){
                                        text += " " + j.value;
                                    }else {
                                        text = j.value;
                                    }
                                });
                            }

                            $("input[name='type_id[" + selectTypeId + "]']").val(value.id);
                            $("input[name='type_name[" + selectTypeId + "]']").val(value.name);
                            $("input[name='type_value[" + selectTypeId + "]']").val(text);
                            $("input[name='type_sort[" + selectTypeId + "]']").val(value.weigh);
                            /*if(value.multiple==true){
                                $('#c-related_goods').val(value.url);
                            }else{
                                $('#c-related_goods').val(value.id+'-'+value.goodsname);
                            }*/
                            /*$('#c-related_goods').val(value.url);
                            var urlArr = [];

                            if(values!==''){
                                urlArr.push(values);
                            }
                            urlArr.push(value.url);
                            var result = urlArr.join(",");
                            console.log(urlArr);
                            $('#c-related_goods').val(result).trigger("change").trigger("validate");*/

                        },
                    });
                });
                //监听商品列表页工具条
                /*table.on('tool(typeTable)', function (obj) { //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
                    var data = obj.data; //获得当前行数据
                    var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
                    if (layEvent === 'selectType') { //选择
                        var value = '';
                        if (data.spec_value.length > 0) {
                            $.each(data.spec_value, function (i, j) {
                                value += j.value + " ";
                            });
                            value = value.substr(0, value.length - 1);
                        }
                        $("input[name='type_id[" + selectTypeId + "]']").val(data.id);
                        $("input[name='type_name[" + selectTypeId + "]']").val(data.name);
                        $("input[name='type_value[" + selectTypeId + "]']").val(value);
                        $("select[name='type_sort[" + selectTypeId + "]']").val(data.sort);
                        form.render('select');
                        layer.close(window.box);
                    }
                });*/

            });
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        addparams: function () {

            Controller.api.bindevent($("form[role=form]"));
        },
        addspec: function () {

            Controller.api.bindevent($("form[role=form]"));
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});

/**
 * 关联属性
 */
function addSpec(id){
    Fast.api.open("goods/Type/addSpec?id=" +id,'关联属性',{
        callback:function(value){
            //在回调函数里可以调用你的业务代码实现前端的各种逻辑和效果
            //console.log(value);
        },
    });

}

/**
 * 关联参数
 * @param id
 */
function addParams(id) {
    Fast.api.open("goods/Type/addParams?id=" + id,'关联参数',{
        callback:function(value){
            //在回调函数里可以调用你的业务代码实现前端的各种逻辑和效果
            //console.log(value);
            //$(".btn-refresh").trigger(“click”);//刷新当前页面的数据
        },
    });
}